package com.dollar.ruyuan_juc.designPattern.guardedSuspension;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

public class GuardedQueue {
    private final Queue<Integer> sourceList;

    public GuardedQueue() {
        this.sourceList = new LinkedBlockingQueue<>();
    }

    /**
     * BlockedQueue 已经实现了线程安全的阻塞获取 get
     *
     * @return
     */
    public synchronized Integer get() {
        while (sourceList.isEmpty()) {
            try {
                wait();    // <--- 如果队列为null，等待。当等待条件满足后会被唤醒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return sourceList.peek();
    }

    public synchronized void put(Integer e) {
        sourceList.add(e);
        notifyAll();  //<--- 通知，继续执行    }
    }
}